package org.gcu.filestorage.configuration;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.gcu.filestorage.api.ErrorCode;
import org.gcu.filestorage.pojo.RequestResult;
import org.gcu.filestorage.uitls.TokenUtil;
import org.jetbrains.annotations.NotNull;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;


@Slf4j
public class TokenCheckInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws IOException {
       log.info("TokenCheckInterceptor#preHandle(), request path is {}", request.getRequestURI());
        String token = request.getHeader("Authorization");
       if (token == null || token.isEmpty() || TokenUtil.parseAccount(token).isEmpty()) {
           response.setCharacterEncoding("UTF-8");
           response.setContentType("application/json;charset=UTF-8");
           RequestResult<Boolean> requestResult = new RequestResult<>();
           requestResult.setData(false);
           requestResult.setResCode(ErrorCode.TOKEN_INCORRECT);
           requestResult.setMessage("Token不正确");
           ObjectMapper objectMapper = new ObjectMapper();
           String json = objectMapper.writeValueAsString(requestResult);
           PrintWriter writer = response.getWriter();
           writer.println(json);
           response.flushBuffer();
           return false;
       }
        return true;
    }
}
